/**
 * 对jquery ajax请求的简易封装
 * Request
 * @author mahuang
 * @param request 
 * @version 1.0
 * 
 * 1. 请求参数格式
 * {
 * 	type: GET/POST/PUT/DELETE
 * 	url: "/api/..."
 * 	data: json data
 *  success: callback
 * }
 * 
 * 2. http请求后端返回response的数据格式如下:
 * response -> {
 * 	resultCode: 1, //请求响应状态, 1: 成功; 0: 失败
 * 	resultMessage: '',
 * 	content: null, //当resultCode=1时, content值为实际响应数据
 * 	errorCode: -1, //当resultCode=0响应失败时, errorCode值表示具体错误码
 * 	errorMessage: ''
 * }
 * 
 * 3. 使用H5特性, 浏览器本地缓存localStorage
 * 
 */

$.SIGN_IN_URI = '/sign-in.html';

//自定义http请求方法与GET/POST/PUT/DELETE的映射集
$._methodStack = {
	'login': 'POST',
	'verify': 'GET',
	'get': 'GET',
	'post': 'POST',
	'put': 'PUT',
	'delete': 'DELETE'
};

$.Request = {
	TOKEN_PREFIX: 'Bearer ',
	AUTHORIZATION: 'Authorization',	
	_dispatch: function(method, request) {
		var _this = this;
		var token = localStorage.getItem(_this.AUTHORIZATION);
		/*
		if(method != 'login' && !token) {
			window.location = $.SIGN_IN_URI;
			return;
		}*/
		
		var _method = $._methodStack[method.toLocaleLowerCase()];
		
		var params = {
			url : '',
			data: {},
			success: null
		}
		$.extend(params, request);

		
		$.ajax({
			async: false,
			url : params.url,
			type : _method,
			contentType : "application/json",
			dataType : "json",
			timeout : 10000,
			data : (_method === 'GET')?params.data:JSON.stringify(params.data),
			beforeSend: function(xhr) {
				//除登录以外的所有请求都需要携带请求头Authorization
				if(method != 'login' && token) {
					xhr.setRequestHeader(_this.AUTHORIZATION, token);
				}
			},
			success : function(response, status, jqXHR) {
				if(response.code == 000001) {

                    alert("服务器端出错");
				} else {
					if(params.success) {
						//服务器端响应成功, 执行success回调函数
						params.success(response);
					}
				}
			},
			error : function(response, status, jqXHR) {
				//这里来处理网络及后端服务错误, 以统一弹框形式展现
				if(response.status == 500) {

                    alert("【500】服务器端出错");
				}

				if(response.status == 404) {

					alert("【404】请求地址不存在");
				}
				
				if(response.status == 401) {
					
					var innerForward = function() {
						var _currentUri = window.location.href;
						if(_currentUri.indexOf($.SIGN_IN_URI) == -1) {
							window.location = $.SIGN_IN_URI;
						}
					}
					//不是verify接口, 则弹框提示, 交互执行后跳转至登录页
					if(method != 'verify') {

                        alert("【401】 请求受限");
					} else {
						//verify接口, 直接跳转至登录页
						innerForward();
					}
				}
				
			}
		});
	},
	GET: function(request) {
		this._dispatch('get', request);
		return this;
	},
	POST: function(request) {
		this._dispatch('post', request);
		return this;
	},
	PUT: function(request) {
		this._dispatch('put', request);
		return this;
	},
	DELETE: function(request) {
		this._dispatch('delete', request);
		return this;
	},
	
	//登录方法
	LOGIN: function(request) {
		var _this = this;
		var params = {
			url : '/api/token',
			data: {
				username: request.username,
				passwd: request.passwd
			},
    		success: function(response) {
				//如果是登录认证请求, 则保存token至cookie中
				_this._token = _this.TOKEN_PREFIX + response.content;
				$.cookie(_this.AUTHORIZATION, _this._token);
    			//浏览器缓存中保存token
    			localStorage.setItem(_this.AUTHORIZATION, _this._token);
    			//跳转至主页
    			window.location = '/';
    		}
		}
		this._dispatch('login', params);
		return this;
	},
	
	//登出方法
	LOGOUT: function() {
		var _token = localStorage.getItem(this.AUTHORIZATION);
		//浏览器缓存中删除token
		localStorage.removeItem(this.AUTHORIZATION);
		//保存token至cookie中
		$.cookie(this.AUTHORIZATION, _token);
		window.location = $.SIGN_IN_URI;
	}

};